#include <workflow/Workflow.h> 
#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpUtil.h>
#include <unistd.h>
#include <signal.h>
#include <ctime>
#include <iostream>
using std::cerr;
using std::cout;
using std::string;

//自定义一个类型
struct SeriesContext
{
	int number;
	string name;
};

// 定义一个全局变量
static WFFacilities::WaitGroup waitGroup(1);
void sighandler(int signum)
{
	waitGroup.done();
}

void CurryCallback(WFTimerTask * task){
	SeriesContext * contex = static_cast<SeriesContext *>(series_of(task)->get_context());
	contex->number = 30;
	contex->name = "Curry";
	cerr << "I am Curry. I pass\n";
}

void JamesCallback(WFTimerTask * task){
	SeriesContext * contex = static_cast<SeriesContext *>(series_of(task)->get_context());
	cerr << "I am James. I got ball from " << contex->number << " " << contex->name << ", I pass\n"; 

	contex->number = 23;
	contex->name = "James";
}

void KobeCallback(WFTimerTask * task){
	SeriesContext * contex = static_cast<SeriesContext *>(series_of(task)->get_context());
	cerr << "I am Kobe. I got ball from " << contex->number << " " << contex->name << ", I shoot\n"; 
}

int main()
{
	signal(SIGINT, sighandler);

	// 创建任务和序列
	WFTimerTask* CurryTask = WFTaskFactory::create_timer_task(3, 0, CurryCallback);
	WFTimerTask* JamesTask = WFTaskFactory::create_timer_task(3, 0, JamesCallback);
	WFTimerTask* KobeTask = WFTaskFactory::create_timer_task(3, 0, KobeCallback);
	SeriesWork * series = Workflow::create_series_work(CurryTask, nullptr);
	series->push_back(JamesTask);
	series->push_back(KobeTask);
	
	// series->set_callback([](const SeriesWork * series){
	// 	// const 说明在序列的回调中，不能添加新的任务了
	// 	SeriesContext * context =  static_cast<SeriesContext *>(series->get_context());
	// 	delete context;
	// });

	// 给contex申请内存，并放入序列中
	SeriesContext * context = new SeriesContext;// 在堆上申请内存
	series->set_context(context); // 将contex存入序列中

	series->set_callback([context](const SeriesWork * series){
		delete context;
	});

	series->start();
	
	waitGroup.wait();
	cout << "finished!\n"; // 不使用std::endl
}